import { createAsyncThunk } from '@reduxjs/toolkit';
import { setLoading, setError } from '../reducers/userReducer';
import api from '../services/api';
import { UserData } from '../types';

export const register = createAsyncThunk(
  'user/register',
  async (userData: UserData, { dispatch }) => {
    dispatch(setLoading(true));
    try {
      const response = await api.registerUser(userData);
      return response; // 返回注册结果
    } catch (error) {
      const errorMessage = api.isAxiosError(error) && error.response
        ? error.response.data.message || 'Registration failed' 
        : '发生错误'; // 提供更具体的错误信息
      dispatch(setError(errorMessage));
      throw error; // 让 Redux 处理 rejected 状态
    } finally {
      dispatch(setLoading(false));
    }
  }
);

export const login = createAsyncThunk(
  'user/login',
  async (userData: UserData, { dispatch }) => {
    dispatch(setLoading(true));
    try {
      const response = await api.loginUser(userData);
      return response; // 返回登录结果
    } catch (error) {
      const errorMessage = api.isAxiosError(error) && error.response
        ? error.response.data.message || 'Login failed' 
        : '发生错误'; // 提供更具体的错误信息 
      dispatch(setError(errorMessage));
      throw error; // 让 Redux 处理 rejected 状态
    } finally {
      dispatch(setLoading(false));
    }
  }
);
